package avicit.bdp.dms.prm.Integration;

import avicit.bdp.common.service.service.IntegrationLogService;
import avicit.bdp.core.util.json.JSONUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 消息处理管理类
 *
 * @author xugb
 * @date 2021/11/5 10:43
 */
@Component
public class HandleManager {
    private static final Logger log = LoggerFactory.getLogger(HandleManager.class);
    @Autowired
    private IntegrationLogService integrationLogService;

    public void handleMessage(String data) {
        if (StringUtils.isBlank(data)) {
            return;
        }

        String infoType = "";
        String infoAction = "";
        try {
            Map<String, Object> map = JSONUtils.toObjectMap(data);

            infoType = MapUtils.getString(map, "infoType", "");
            infoAction = MapUtils.getString(map, "infoAction", "");

            List<Map<String, Object>> list = (List<Map<String, Object>>) MapUtils.getObject(map, "infoData");
            BaseMessageHandle handle = null;
            if ("dataSourceType".equalsIgnoreCase(infoType)) {
                handle = new DataSourceTypeHandle();
            } else if ("dataSource".equalsIgnoreCase(infoType)) {
                handle = new DataSourceHandle();
            } else if ("tableCatalog".equalsIgnoreCase(infoType)) {
                handle = new TableTypeHandle();
            } else if ("table".equalsIgnoreCase(infoType)) {
                handle = new TableHandle();
            } else {
                // TODO 支持通用的表消息处理  需要定义对应消息类型的数据源、表信息、字段、字段类型
                //handle = new DefaultHandle();
            }


            if (handle != null) {
                handle.excute(infoType, infoAction, list);
            }

            // 接收消息保存日志
            //IntegrationInfoUtils.getInstance().handleSubscribeLog(infoType, infoAction, data, 1);

        } catch (Exception e) {
           log.error(e.getMessage(), e);
            // 接收消息保存日志
            //IntegrationInfoUtils.getInstance().handleSubscribeLog(infoType, infoAction, data, 0);
        }


    }

}
